package com.jinlia.show.modules.base.system.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.common.core.exception.MyRuntimeException;
import com.jinlia.show.modules.base.constant.*;
import com.jinlia.show.modules.base.model.bo.DaDaAddOrderRequest;
import com.jinlia.show.modules.base.model.bo.DaDaProduct;
import com.jinlia.show.modules.base.model.po.DeliveryOrderPO;
import com.jinlia.show.modules.base.model.po.ErrandOrderPO;
import com.jinlia.show.modules.base.model.po.OrderItemPO;
import com.jinlia.show.modules.base.model.po.OrderPO;
import com.jinlia.show.modules.base.model.query.ErrandOrderQuery;
import com.jinlia.show.modules.base.model.vo.ErrandOrderVO;
import com.jinlia.show.modules.base.system.entity.DeliveryOrder;
import com.jinlia.show.modules.base.system.entity.ErrandDadaCallback;
import com.jinlia.show.modules.base.system.entity.ErrandOrder;
import com.jinlia.show.modules.base.system.mapper.ErrandOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ErrandOrderMapperService extends ServiceImpl<ErrandOrderMapper, ErrandOrder> {
    @Value("${dada.uri}")
    public String uri;
    @Value("${dada.app_key}")
    public String appKey;
    @Value("${dada.app_secret}")
    public String appSecret;
    @Value("${dada.source_id}")
    public String sourceId;
    @Value("${dada.shop_no}")
    public String shopNo;
    @Value("${dada.callback}")
    public String callback;
    @Autowired
    private RestTemplate dadaRestTemplate;
    @Autowired
    private OrderMapperService orderMapperService;
    @Autowired
    private OrderItemMapperService orderItemMapperService;
    @Autowired
    private DeliveryOrderMapperService deliveryOrderMapperService;
    @Autowired
    private OrderLogMapperService orderTrackMapperService;
    @Autowired
    private ErrandDadaCallbackMapperService errandDadaCallbackMapperService;
    /**
     * 下单接口
     */
    private String addOrderUri = "/api/order/addOrder"; //下单接口
    private String orderQuery = "/api/order/status/query"; //订单查询接口
    private String transporterPosition = "/api/order/transporter/position"; //查询棋手位置=>返回经纬度信息
    private String transporterTrack = "/api/order/transporter/track"; //查询棋手位置=>返回H5信息
    private String queryDeliverFee = "/api/order/queryDeliverFee"; //查询运费
    private String addAfterQuery = "/api/order/addAfterQuery";//查询运费后下单
    private String cancelOrder = "/api/order/formalCancel";//取消订单

    public ErrandOrder queryDeliverFee(Long orderId) {
        DeliveryOrder oneDeliveryOrder = deliveryOrderMapperService.lambdaQuery()
                .eq(DeliveryOrder::getCurrentErrandStatus, 0)
                .eq(DeliveryOrder::getOrderId, orderId)
                .one();
        if (oneDeliveryOrder == null) {
            throw new MyRuntimeException("自取模式,无需配送!!!");
        }
        //判断是否已存在
        List<ErrandOrder> list = this.lambdaQuery()
                .eq(ErrandOrder::getDeliveryOrderId, oneDeliveryOrder.getOrderId())
                .eq(ErrandOrder::getEnableStatus, EnableStatusEnum.ENABLE.getValue()) //进行中的
                .notIn(ErrandOrder::getErrandOrderStatus, 5, 1000)
                .list();
        if (!CollectionUtils.isEmpty(list)) {
            throw new MyRuntimeException("701", "配送单已形成!!!");
        }
//        DeliveryOrderPO details = deliveryOrderMapperService.getDetails(deliveryOrderId);
//        if (DeliveryTypeEnum.SELF_PICT.getValue().equals(oneDeliveryOrder.getDeliveryType())) {
//            throw new MyRuntimeException("自取模式,无需配送!!!");
//        }
        ErrandOrder errandOrder = this.lambdaQuery()
                .eq(ErrandOrder::getDeliveryOrderId, oneDeliveryOrder.getOrderId())
                .eq(ErrandOrder::getEnableStatus, EnableStatusEnum.WAIT_ENABLE.getValue())
                .one();
        if (Objects.isNull(errandOrder)) {
            errandOrder = new ErrandOrder();
            errandOrder.setDeliveryOrderId(oneDeliveryOrder.getId());
            errandOrder.setOrderId(orderId);
            errandOrder.setEnableStatus(EnableStatusEnum.WAIT_ENABLE.getValue());
            errandOrder.setOrderMethod(1);//默认0
            this.save(errandOrder);
        }
        Object body = this.buildAddOrderBody(oneDeliveryOrder, errandOrder);
        log.info("buildBody签名前:{}", JSON.toJSON(body));
        //发起请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(generateParams(body), headers);
        errandOrder.setRequest(JSON.toJSONString(body));//记录请求
        log.info("地址url = {},buildBody签名后:{}", uri + queryDeliverFee,JSON.toJSON(mapHttpEntity));
        ResponseEntity<JSONObject> stringResponseEntity = dadaRestTemplate.postForEntity(uri + queryDeliverFee, mapHttpEntity, JSONObject.class);
        if (stringResponseEntity.getStatusCode().equals(HttpStatus.OK) &&
                Boolean.TRUE.equals(stringResponseEntity.getBody().getBoolean("success"))
        ) {
            JSONObject jSONObjectBody = stringResponseEntity.getBody();
            errandOrder.setDeliveryFee(new BigDecimal(jSONObjectBody.getJSONObject("result").getString("fee")));
            errandOrder.setErrandSourceNum(jSONObjectBody.getJSONObject("result").getString("deliveryNo"));
            errandOrder.setErrandDistance(jSONObjectBody.getJSONObject("result").getString("distance"));
            errandOrder.setErrandOrderStatus(ErrandOrderStatusEnum.A0.getValue());
            this.updateById(errandOrder);
            return errandOrder;
        } else {
            throw new MyRuntimeException("601", "达达跑腿询价失败!!!");
        }
    }

    @Transactional
    public JSONObject addAfterQuery(Long errandOrderId) {
        ErrandOrder oneErrandOrder = this.getById(errandOrderId);
        if (oneErrandOrder.getEnableStatus() != EnableStatusEnum.WAIT_ENABLE.getValue()) {
            throw new MyRuntimeException("订单失效!!!");
        }
        // 构建基本信息
        Map<String, String> body = new HashMap();
        body.put("deliveryNo", oneErrandOrder.getErrandSourceNum());
        // 构建真正的api接口参数
        //发起请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(generateParams(body), headers);
        ResponseEntity<JSONObject> stringResponseEntity = dadaRestTemplate.postForEntity(uri + addAfterQuery, mapHttpEntity, JSONObject.class);
        if (stringResponseEntity.getStatusCode().equals(HttpStatus.OK) &&
                Boolean.TRUE.equals(stringResponseEntity.getBody().getBoolean("success"))
        ) {
            oneErrandOrder.setRequestSecond(JSON.toJSONString(body));
            oneErrandOrder.setResponseLast(stringResponseEntity.getBody().toJSONString());
            oneErrandOrder.setErrandOrderStatus(ErrandOrderStatusEnum.A.getValue());
            oneErrandOrder.setEnableStatus(EnableStatusEnum.ENABLE.getValue());
            this.updateById(oneErrandOrder);
            //自动接单
            DeliveryOrder deliveryOrder = new DeliveryOrder();
            deliveryOrder.setId(oneErrandOrder.getDeliveryOrderId());
            deliveryOrder = deliveryOrderMapperService.confirmDeliveryOrder(deliveryOrder, false);//商户接单
//            //记录跑腿
//            deliveryOrderMapperService.lambdaUpdate()
//                    .eq(DeliveryOrder::getId, deliveryOrder.getId())
//                    .set(DeliveryOrder::getDeliveryType, DeliveryTypeEnum.OTHER21_PICT.getValue())
//                    .update();
        } else {
            log.info(stringResponseEntity.getBody().toJSONString());
            throw new MyRuntimeException("601", stringResponseEntity.getBody().getString("msg"));
        }
        //解析结果
        return stringResponseEntity.getBody();

    }

    /**
     * 直接下单
     */
    public JSONObject addOrder(Long deliveryOrderId) {
        ErrandOrder one = this.lambdaQuery()
                .eq(ErrandOrder::getDeliveryOrderId, deliveryOrderId)
                .one();
        if (one != null) {
            throw new MyRuntimeException("配送单已存在!!!");
        }
        DeliveryOrderPO details = deliveryOrderMapperService.getDetails(deliveryOrderId);
//        if (DeliveryTypeEnum.SELF_PICT.getValue().equals(details.getDeliveryType())) {
//            throw new MyRuntimeException("自取模式,无需配送!!!");
//        }

        //新增跑腿达达订单
        ErrandOrder deliveryDada = new ErrandOrder();
        deliveryDada.setDeliveryOrderId(deliveryOrderId);
        DeliveryOrder byId = deliveryOrderMapperService.getById(deliveryOrderId);
        deliveryDada.setOrderId(byId.getOrderId());
        deliveryDada.setOrderMethod(1);//默认0
        deliveryDada.setEnableStatus(EnableStatusEnum.WAIT_ENABLE.getValue());
        this.save(deliveryDada);
        Object body = this.buildAddOrderBody(details, deliveryDada);
        log.info("buildBody:{}", JSON.toJSON(body));
        // 构建真正的api接口参数
        Map<String, Object> params = generateParams(body);
        //发起请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JSONObject> stringResponseEntity = dadaRestTemplate.postForEntity(uri + addOrderUri, mapHttpEntity, JSONObject.class);
        if (stringResponseEntity.getStatusCode().equals(HttpStatus.OK) &&
                Boolean.TRUE.equals(stringResponseEntity.getBody().getBoolean("success"))
        ) {
            //新增跑腿达达订单
            this.save(deliveryDada);
            deliveryDada.setRequest(JSON.toJSON(body).toString());
            deliveryDada.setResponseLast(stringResponseEntity.getBody().toJSONString());
            this.updateById(deliveryDada);
            //自动接单
            DeliveryOrder deliveryOrder = new DeliveryOrder();
            deliveryOrder.setId(deliveryOrderId);
            deliveryOrder = deliveryOrderMapperService.confirmDeliveryOrder(deliveryOrder, false);//商户接单
            //记录跑腿
            deliveryOrderMapperService.lambdaUpdate()
                    .eq(DeliveryOrder::getId, deliveryOrder.getId())
                    .set(DeliveryOrder::getCurrentErrandType, ErrandTypeEnum.DADA.getValue())
                    .update();
            //订单操作记录
            orderTrackMapperService.addOrderLog("PT", deliveryOrder.getOrderId(),
                    "下单达达跑腿", "待配送");
        }
        //解析结果
        return stringResponseEntity.getBody();
    }

    /**
     * 查询订单状态
     *
     * @return
     */
    public JSONObject orderQuery(Long deliveryOrderId) {

        // 构建基本信息
        Map<String, String> body = Collections.singletonMap("order_id", String.valueOf(deliveryOrderId));
        //发起请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(generateParams(body), headers);
        ResponseEntity<JSONObject> stringResponseEntity = dadaRestTemplate.postForEntity(uri + orderQuery, mapHttpEntity, JSONObject.class);
        if (stringResponseEntity.getStatusCode().equals(HttpStatus.OK) &&
                Boolean.TRUE.equals(stringResponseEntity.getBody().getBoolean("success"))
        ) {
            //兼容下单成功单接单失败的场景
            JSONObject result = stringResponseEntity.getBody().getJSONObject("result");
            this.lambdaUpdate()
                    .set(ErrandOrder::getResponseLast, stringResponseEntity.getBody().toJSONString())
                    .set(StringUtils.hasLength(result.getString("statusCode")),
                            ErrandOrder::getErrandOrderStatus, result.getString("statusCode"))
                    .set(StringUtils.hasLength(result.getString("transporterName")),
                            ErrandOrder::getTransporterName, result.getString("transporterName"))
                    .set(StringUtils.hasLength(result.getString("transporterPhone")),
                            ErrandOrder::getTransporterPhone, result.getString("transporterPhone"))
                    .set(StringUtils.hasLength(result.getString("deliveryFee")),
                            ErrandOrder::getDeliveryFee, new BigDecimal(result.getString("deliveryFee")))
                    .eq(ErrandOrder::getDeliveryOrderId, deliveryOrderId)
                    .update(new ErrandOrder());//new ErrandOrder() 自动填充
        }
        System.out.println(stringResponseEntity.getBody());
        return stringResponseEntity.getBody();
    }

    /**
     * 查询棋手位置
     *
     * @return
     */
    public JSONObject transporterPosition(Long deliveryOrderId) {

        // 构建基本信息
        Map<String, List<String>> body = Collections.singletonMap("orderIds", Collections.singletonList(String.valueOf(deliveryOrderId)));
        // 构建真正的api接口参数
        Map<String, Object> params = generateParams(body);
        //发起请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JSONObject> stringResponseEntity = dadaRestTemplate.postForEntity(uri + transporterPosition, mapHttpEntity, JSONObject.class);
        //解析结果
        System.out.println(stringResponseEntity.getBody());
        return stringResponseEntity.getBody();
    }

    /**
     * 查询棋手返回H5页面
     *
     * @return
     */
    public JSONObject transporterTrack(Long deliveryOrderId) {
        // 构建基本信息
        Map<String, String> body = Collections.singletonMap("order_id", String.valueOf(deliveryOrderId));
        // 构建真正的api接口参数
        Map<String, Object> params = generateParams(body);
        //发起请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JSONObject> stringResponseEntity = dadaRestTemplate.postForEntity(uri + transporterTrack, mapHttpEntity, JSONObject.class);
        //解析结果
        System.out.println(stringResponseEntity.getBody());
        return stringResponseEntity.getBody();
    }

    /**
     * 取消订单
     *
     * @param errandOrder
     * @return
     */
    public JSONObject cancelOrder(ErrandOrder errandOrder) {
        ErrandOrder byIdErrandOrder = this.getById(errandOrder.getId());
        // 构建基本信息
        Map<String, String> body = new HashMap<>();
        body.put("order_id", byIdErrandOrder.getDeliveryOrderId().toString());
        body.put("cancel_reason_id", errandOrder.getCancelCode());
        body.put("cancel_reason", errandOrder.getCancelReason());
        // 构建真正的api接口参数
        Map<String, Object> params = generateParams(body);
        //发起请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JSONObject> stringResponseEntity = dadaRestTemplate.postForEntity(uri + cancelOrder, mapHttpEntity, JSONObject.class);
        //解析结果，并更新订单
        if (stringResponseEntity.getStatusCode().equals(HttpStatus.OK) &&
                Boolean.TRUE.equals(stringResponseEntity.getBody().getBoolean("success"))
        ) {
            ErrandDadaCallback errandDadaCallback = new ErrandDadaCallback();
            errandDadaCallback.setCallbackTime(LocalDateTime.now());
            errandDadaCallback.setErrandOrderId(errandOrder.getId());
            errandDadaCallback.setErrandStatus(ErrandOrderStatusEnum.E.getValue());
            errandDadaCallbackMapperService.save(errandDadaCallback);
            this.lambdaUpdate()
                    .eq(ErrandOrder::getId, errandOrder.getId())
                    .set(ErrandOrder::getErrandOrderStatus, ErrandOrderStatusEnum.E.getValue())
                    .set(ErrandOrder::getCancelCode, errandOrder.getCancelCode())
                    .set(ErrandOrder::getCancelReason, errandOrder.getCancelReason())
                    .update(new ErrandOrder());
        } else {
            throw new MyRuntimeException("601", stringResponseEntity.getBody().getString("msg"));
        }
        return stringResponseEntity.getBody();
    }

    /**
     * 构造下单信息
     *
     * @param deliveryOrder
     * @return
     */
    private Object buildAddOrderBody(DeliveryOrder deliveryOrder, ErrandOrder errandOrder) {
        OrderPO orderPO = orderMapperService.getPOByIds(deliveryOrder.getOrderId()).get(0);
        ArrayList<DaDaProduct> daDaProducts = new ArrayList<>();
        List<OrderItemPO> items = orderPO.getItems();
        for (OrderItemPO item : items) {
            daDaProducts.add(DaDaProduct.builder()
                    .skuName(item.getGoodsName())
                    .count(Double.valueOf(item.getGoodsNum())) //数量
                    .srcProductNo(String.valueOf(item.getGoodsId())) //商品编码
//                    .unit("瓶") //默认件
                    .build());
        }
        return DaDaAddOrderRequest.builder()
                .shopNo(shopNo)
                .originId(deliveryOrder.getId().toString()) //原始订单号
                .cargoPrice(orderPO.getReceivableMoney()) //订单价格
                .cargoWeight(1.2) //商品重量kg
                .prepay(0) //是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
                .receiverName(deliveryOrder.getUserName())
                .receiverAddress(deliveryOrder.getDeliveryAddress())
                .receiverPhone(deliveryOrder.getUserPhone())
                .receiverLat(Double.valueOf(deliveryOrder.getDeliveryAddressLatitude()))
                .receiverLng(Double.valueOf(deliveryOrder.getDeliveryAddressLongitude()))
                .callback(String.format(callback, errandOrder.getId()))
                .productList(daDaProducts)
                //青岛#S20241125A01
                .originMark("青岛")
                .originMarkNo(orderPO.getOrderNum()) //青岛#S20241125A01
                .pickUpPos(String.format("订单号:%S_%S*", orderPO.getOrderNum(), orderPO.getUserName().substring(0, 1))) //订单备注
                .fetchCode(orderPO.getOrderNum().substring(orderPO.getOrderNum().length() - 3)) //取件码
                .build();
    }

    /**
     * 生成签名(具体参考文档: http://newopen.imdada.cn/#/quickStart/develop/safety?_k=kklqac)
     */
    private String signature(Map<String, Object> data, String appSecret) {
        // 请求参数按照【属性名】字典升序排序后，按照属性名+属性值拼接
        String signStr = data.keySet().stream()
                .sorted()
                .map(it -> String.format("%s%s", it, data.get(it)))
                .collect(Collectors.joining(""));
        // 拼接后的结果首尾加上appSecret
        String privateSignStr = appSecret + signStr + appSecret;
        // MD5加密并转为大写
        return DigestUtils.md5DigestAsHex(
                privateSignStr.getBytes(StandardCharsets.UTF_8)).toUpperCase();
    }

    /**
     * 构建真正的api接口参数
     *
     * @param body 接口的body参数内容
     * @return 构建真正的api接口参数
     */
    private Map<String, Object> generateParams(Object body) {
        Map<String, Object> data = new HashMap<>();
        data.put("source_id", sourceId);
        data.put("app_key", appKey);
        data.put("timestamp", LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond());
        data.put("format", "json");
        data.put("v", "1.0");
        data.put("body", JSON.toJSONString(body));
        data.put("signature", signature(data, appSecret));
        return data;
    }

    public ErrandOrderPO getPOById(Long id) {
        ErrandOrder byId = this.getById(id);
        ErrandOrderPO errandOrderPO = ErrandOrderPO.fromEntity(byId);
        errandOrderPO.setDeliveryOrder(deliveryOrderMapperService.getDetails(errandOrderPO.getDeliveryOrderId()));
        errandOrderPO.setSaleOrder(orderMapperService.getById(errandOrderPO.getDeliveryOrder().getOrderId()));
        List<ErrandDadaCallback> listErrandDadaCallback = errandDadaCallbackMapperService.lambdaQuery()
                .eq(ErrandDadaCallback::getErrandOrderId, id)
                .list();
        errandOrderPO.setErrandDadaCallbacks(listErrandDadaCallback);
        return errandOrderPO;
    }

    public JSONObject reAddOrder(Long errandOrderId) {
        ErrandOrder oldErrandOrder = this.getById(errandOrderId);
        if (oldErrandOrder.getErrandOrderStatus() != 5) {
            throw new MyRuntimeException("请先取消跑腿!!!");
        }
        //新增跑腿达达订单
        ErrandOrder newErrandOrder = new ErrandOrder();
        newErrandOrder.setDeliveryOrderId(oldErrandOrder.getDeliveryOrderId());
        newErrandOrder.setOrderMethod(2);//默认0
        newErrandOrder.setEnableStatus(EnableStatusEnum.WAIT_ENABLE.getValue());
        this.save(newErrandOrder);
        DeliveryOrderPO details = deliveryOrderMapperService.getDetails(oldErrandOrder.getDeliveryOrderId());
        Object body = this.buildReAddOrderBody(details, newErrandOrder);
        log.info("buildBody:{}", JSON.toJSON(body));
        // 构建真正的api接口参数
        Map<String, Object> params = generateParams(body);
        //发起请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JSONObject> stringResponseEntity = dadaRestTemplate.postForEntity(uri + addOrderUri, mapHttpEntity, JSONObject.class);
        if (stringResponseEntity.getStatusCode().equals(HttpStatus.OK) &&
                Boolean.TRUE.equals(stringResponseEntity.getBody().getBoolean("success"))
        ) {
            newErrandOrder.setEnableStatus(EnableStatusEnum.ENABLE.getValue());
            newErrandOrder.setRequest(JSON.toJSON(body).toString());
            newErrandOrder.setResponseLast(stringResponseEntity.getBody().toJSONString());
            this.updateById(newErrandOrder);
            //记录跑腿
            deliveryOrderMapperService.lambdaUpdate()
                    .eq(DeliveryOrder::getId, details.getId())
                    .set(DeliveryOrder::getCurrentErrandType, ErrandTypeEnum.DADA.getValue())
                    .set(DeliveryOrder::getCurrentErrandId, newErrandOrder.getId())
                    .update();
        }
        //解析结果
        return stringResponseEntity.getBody();
    }

    private Object buildReAddOrderBody(DeliveryOrderPO deliveryOrderPO, ErrandOrder newErrandOrder) {
        ArrayList<DaDaProduct> daDaProducts = new ArrayList<>();
        List<OrderItemPO> items = deliveryOrderPO.getOrderPO().getItems();
        for (OrderItemPO item : items) {
            daDaProducts.add(DaDaProduct.builder()
                    .skuName(item.getGoodsName())
                    .count(Double.valueOf(item.getGoodsNum())) //数量
                    .srcProductNo(String.valueOf(item.getGoodsId())) //商品编码
//                    .unit("瓶") //默认件
                    .build());
        }

        return DaDaAddOrderRequest.builder()
                .shopNo(shopNo)
                .originId(deliveryOrderPO.getId().toString()) //原始订单号
                .cargoPrice(deliveryOrderPO.getOrderPO().getReceivableMoney()) //订单价格
                .cargoWeight(1.2) //商品重量kg
                .prepay(0) //是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
                .receiverName(deliveryOrderPO.getUserName())
                .receiverAddress(deliveryOrderPO.getDeliveryAddress())
                .receiverPhone(deliveryOrderPO.getUserPhone())
                .receiverLat(Double.valueOf(deliveryOrderPO.getDeliveryAddressLatitude()))
                .receiverLng(Double.valueOf(deliveryOrderPO.getDeliveryAddressLongitude()))
                .callback(callback + newErrandOrder.getId())
                .productList(daDaProducts)
                .build();
    }

    public Page<ErrandOrderVO> getPagePO(ErrandOrderQuery queryParams) {
        Page<ErrandOrderVO> page = new Page<>(queryParams.getCurrent(), queryParams.getSize());
        Page<ErrandOrderVO> pageVO = this.getBaseMapper().getPageVO(page, queryParams);
        return pageVO;
    }

    public List<ErrandOrderPO> getList(ErrandOrderQuery errandOrderQuery) {
        List<ErrandOrder> list = this.lambdaQuery()
                .eq(Objects.nonNull(errandOrderQuery.getOrderId()), ErrandOrder::getOrderId, errandOrderQuery.getOrderId())
                .eq(Objects.nonNull(errandOrderQuery.getDeliveryOrderNum()), ErrandOrder::getDeliveryOrderId, errandOrderQuery.getSaleOrderNum())
                .list();
        List<ErrandOrderPO> collect = list.stream().map(ErrandOrderPO::fromEntity).collect(Collectors.toList());
        for (ErrandOrderPO errandOrderPO : collect) {
            List<ErrandDadaCallback> listErrandDadaCallback = errandDadaCallbackMapperService.lambdaQuery()
                    .eq(ErrandDadaCallback::getErrandOrderId, errandOrderPO.getId())
                    .list();
            errandOrderPO.setErrandDadaCallbacks(listErrandDadaCallback);
        }
        return collect;
    }
}
